import { _decorator, Component, Node, resources, SpriteFrame, Prefab, AudioClip, log } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ResourceManager')
export class ResourceManager extends Component {
    // 单例对象
    private static instance: ResourceManager = null;

    // 当前加载的资源缓存，使用资源路径作为键
    private resourceCache: Map<string, any> = new Map();

    // 私有构造函数，防止外部实例化
    private constructor() {
        super();
    }

    // 获取单例实例
    public static getInstance(): ResourceManager {
        if (!ResourceManager.instance) {
            ResourceManager.instance = new ResourceManager();
        }
        return ResourceManager.instance;
    }

    // 动态加载资源，支持不同类型资源
    public loadResource<T>(path: string, type: any, onLoadComplete: (asset: T) => void) {
        // 如果资源已经加载过，则直接返回缓存的资源
        if (this.resourceCache.has(path)) {
            log(`Resource at ${path} already loaded from cache.`);
            onLoadComplete(this.resourceCache.get(path));
            return;
        }

        // 否则，动态加载资源
        resources.load(`img/UI_STAR_NORMAL/spriteFrame`, SpriteFrame, (err, spriteFrame) => {
            if (err) {
                log(`Failed to load resource at ${path}: ${err.message}`);
                return;
            }
            // 将加载的资源缓存
            this.resourceCache.set(path, asset);
            log(`Resource at ${path} loaded and cached.`);
            onLoadComplete(asset);
        });
    }

    // 清理资源缓存
    public clearCache(path?: string) {
        if (path) {
            this.resourceCache.delete(path);
            log(`Cache cleared for resource: ${path}`);
        } else {
            this.resourceCache.clear();
            log("All resource cache cleared.");
        }
    }
}


